package com.ytktt.study.week12.task4.util;

import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 当天日期格式化字符串
 *
 * @author ytk
 */
@Component
public class CurDateStringUtil {

    private String curDate;
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");

    public CurDateStringUtil() {
        this.curDate = this.dtf.format(LocalDate.now());
    }

    public String getCurDateString() {
        ReentrantReadWriteLock.ReadLock readLock = this.lock.readLock();
        readLock.lock();
        try {
            return this.curDate;
        } finally {
            readLock.unlock();
        }
    }

    public void genCurDateString() {
        ReentrantReadWriteLock.WriteLock writeLock = this.lock.writeLock();
        writeLock.lock();
        try {
            this.curDate = this.dtf.format(LocalDate.now());
        } finally {
            writeLock.unlock();
        }
    }

    public DateTimeFormatter getDateTimeFormatter() {
        return this.dtf;
    }
}
